import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../config/const.dart';
import '../../../config/r.dart';
import '../../../l10n/local.dart';
import '../controller.dart';

// 手机号登录表单
class PhoneLoginForm extends StatefulWidget {
  // 切换认证模式回调
  final Function(AuthMode) onSwitchAuthMode;

  // 发送验证码，把手机号传出去，同时外面传进来一个bool值表示是否发送成功
  final Function(String, Function(bool)) sendVerificationCodeAction;

  // 使用手机号
  final Function(String, String) loginWithPhoneAction;

  // 三方登录
  final Function() thirdLoginAction;

  // 区域号
  final String areaCode;

  final Function() areaCodeOnTap;

  // 修改手机号与注册类似，所以直接复用注册的逻辑
  final bool isRegisterMode;

  const PhoneLoginForm({
    super.key,
    required this.onSwitchAuthMode,
    required this.sendVerificationCodeAction,
    required this.loginWithPhoneAction,
    required this.thirdLoginAction,
    required this.areaCode,
    required this.areaCodeOnTap,
    this.isRegisterMode = true,
  });

  @override
  State<PhoneLoginForm> createState() => _PhoneLoginFormState();
}

class _PhoneLoginFormState extends State<PhoneLoginForm> {
  final _formKey = GlobalKey<FormState>();
  final _phoneController = TextEditingController();
  final _verificationCodeController = TextEditingController();
  bool _countdownActive = false;
  int _countdownSeconds = 60;
  bool _isSendAction = false;

  void _startCountdown() {
    if (_countdownActive) return;

    _isSendAction = true;

    if (!_formKey.currentState!.validate()) {
      return;
    }

    widget.sendVerificationCodeAction(
      _phoneController.text.trim(),
      (success) {
        if (success) {
          setState(() {
            _countdownActive = true;
            _countdownSeconds = 60;
          });

          // Start countdown timer
          Future.delayed(const Duration(seconds: 1), () {
            if (mounted) _updateCountdown();
          });
        }
      },
    );
  }

  void _updateCountdown() {
    // 关键修复：检查组件是否仍然挂载
    if (!mounted) return;

    setState(() {
      _countdownSeconds--;
    });

    if (_countdownSeconds > 0) {
      Future.delayed(const Duration(seconds: 1), _updateCountdown);
    } else {
      setState(() {
        _countdownActive = false;
      });
    }
  }

  void _submit() async {
    _isSendAction = false;
    if (!_formKey.currentState!.validate()) {
      return;
    }
    widget.loginWithPhoneAction(
      _phoneController.text.trim(),
      _verificationCodeController.text.trim(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (widget.isRegisterMode) ...[
            Text(
              local
                  .after_logging_in_the_system_will_automatically_register_a_new_account_for_you,
              style: const TextStyle(
                color: Colors.grey,
              ),
            ),
            SizedBox(height: 24.w),
          ],
          // Phone Field
          TextFormField(
            controller: _phoneController,
            keyboardType: TextInputType.phone,
            decoration: InputDecoration(
              labelStyle: TextStyle(
                  color: const Color(0xFFEEEEEE).withOpacity(0.6),
                  fontSize: 14),
              labelText: local.phone_number,
              prefixIcon: ClipRRect(
                borderRadius: BorderRadius.circular(8.w),
                child: InkWell(
                  onTap: () {
                    widget.areaCodeOnTap();
                  },
                  child: IntrinsicWidth(
                    child: Container(
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.symmetric(horizontal: 8.w),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(width: 2.w),
                          Text(
                            widget.areaCode,
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const Icon(
                            Icons.arrow_drop_down,
                            size: 18,
                          ),
                          SizedBox(width: 4.w),
                          Container(
                            height: 24.w,
                            width: 1,
                            color: Colors.grey.withOpacity(0.5),
                          ),
                          const SizedBox(width: 2),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              counterText: '',
            ),
            validator: (value) {
              if (value == null ||
                  value.isEmpty ||
                  value.length < phoneMinLength) {
                return local.please_enter_valid_phone_number;
              }
              return null;
            },
          ),
          SizedBox(height: 16.w),

          // Verification Code Field
          TextFormField(
            controller: _verificationCodeController,
            keyboardType: TextInputType.number,
            maxLength: verificationCodeLength,
            decoration: InputDecoration(
              labelStyle: TextStyle(
                  color: const Color(0xFFEEEEEE).withOpacity(0.6),
                  fontSize: 14),
              labelText: local.verification_code,
              prefixIcon: Image.asset(R.codeIcon, width: 18, height: 18),
              suffixIcon: TextButton(
                onPressed: _countdownActive ? null : _startCountdown,
                child: Text(
                  _countdownActive ? '$_countdownSeconds s' : local.send,
                  style: TextStyle(
                    color: _countdownActive ? Colors.grey : LxCol.theme,
                  ),
                ),
              ),
              counterText: '',
            ),
            validator: (value) {
              if (_isSendAction) return null;
              if (value == null ||
                  value.isEmpty ||
                  value.length != verificationCodeLength) {
                return local.please_enter_valid_code(6);
              }
              return null;
            },
          ),
          SizedBox(height: widget.isRegisterMode ? 24 : 100),

          // Register Button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _submit,
              style: ElevatedButton.styleFrom(
                backgroundColor: LxCol.theme.withOpacity(0.8),
                padding: EdgeInsets.symmetric(vertical: 16.w),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: Text(
                  widget.isRegisterMode ? local.phone_login : local.confirm,
                  style: const TextStyle(fontSize: 16, color: Colors.white)),
            ),
          ),
          if (widget.isRegisterMode) ...[
            SizedBox(
              width: double.infinity,
              child: Wrap(
                spacing: 2.0.w, // 水平间距
                runSpacing: 0.0, // 垂直间距
                crossAxisAlignment: WrapCrossAlignment.center,
                alignment: WrapAlignment.start,
                children: [
                  Text(
                    local.no_account,
                    style: TextStyle(
                        color: Colors.white.withOpacity(0.6), fontSize: 12),
                  ),
                  TextButton(
                    onPressed: () {
                      widget.onSwitchAuthMode(AuthMode.emailRegister);
                    },
                    child: Text(
                      local.register_account,
                      style: TextStyle(
                          color: Colors.white.withOpacity(0.6), fontSize: 12),
                    ),
                  ),
                ],
              ),
            ),

            // Divider
            Row(
              children: [
                const Expanded(child: Divider()),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8.w),
                  child: Text(
                    local.or,
                    style: TextStyle(
                        color: Colors.white.withOpacity(0.6), fontSize: 14),
                  ),
                ),
                const Expanded(child: Divider()),
              ],
            ),
            SizedBox(height: 16.w),
            Row(
              children: [
                // Google login button
                Expanded(
                  child: OutlinedButton(
                    onPressed: () {
                      widget.thirdLoginAction();
                    },
                    style: OutlinedButton.styleFrom(
                      foregroundColor: Colors.grey,
                      side: const BorderSide(color: Colors.grey),
                      padding: EdgeInsets.symmetric(vertical: 16.w),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Platform.isAndroid
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                R.googleLoginIcon,
                                width: 25,
                                height: 25,
                              ).colorFiltered(
                                color: Colors.white.withOpacity(0.6),
                              ),
                              SizedBox(width: 8.w),
                              Flexible(
                                child: Text(
                                  local.google_login,
                                  softWrap: true,
                                  overflow: TextOverflow.visible,
                                  style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.white.withOpacity(0.6)),
                                ),
                              ),
                            ],
                          )
                        : Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                R.appleLoginIcon,
                                width: 25,
                                height: 25,
                              ).colorFiltered(
                                color: Colors.white.withOpacity(0.6),
                              ),
                              SizedBox(width: 8.w),
                              Flexible(
                                child: Text(
                                  local.apple_login,
                                  softWrap: true,
                                  overflow: TextOverflow.visible,
                                  style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.white.withOpacity(0.6)),
                                ),
                              ),
                            ],
                          ),
                  ),
                ),
                SizedBox(width: 16.w),
                // Phone login button
                Expanded(
                  child: OutlinedButton(
                    onPressed: () {
                      widget.onSwitchAuthMode(AuthMode.emailLogin);
                    },
                    style: OutlinedButton.styleFrom(
                      foregroundColor: Colors.grey,
                      side: const BorderSide(color: Colors.grey),
                      padding: EdgeInsets.symmetric(vertical: 16.w),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          R.emailIcon,
                          width: 25,
                          height: 25,
                        ).colorFiltered(
                          color: Colors.white.withOpacity(0.6),
                        ),
                        SizedBox(width: 8.w),
                        Flexible(
                          child: Text(
                            local.email_login,
                            softWrap: true,
                            overflow: TextOverflow.visible,
                            style: TextStyle(
                                fontSize: 14,
                                color: Colors.white.withOpacity(0.6)),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ],
      ),
    );
  }
}
